import sqlite3
import os
from contextlib import contextmanager
from fastapi import Depends

# 同步版本（后续可升级为异步）
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DB_DIR = os.path.join(BASE_DIR, "03阶段-基础版-原生SQL操作（SQLite示例）")
DB_FILE = "test.db"
DATABASE = os.path.join(DB_DIR, DB_FILE)

# 确保目录存在
os.makedirs(DB_DIR, exist_ok=True)

def create_connection():
    """创建新的数据库连接"""
    conn = sqlite3.connect(DATABASE)
    conn.row_factory = sqlite3.Row
    return conn

def check_tables(conn):
    """检查表是否存在"""
    try:
        cursor = conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='items'")
        return cursor.fetchone() is not None
    except sqlite3.Error:
        return False

def init_db():
    """初始化数据库（只执行一次）"""
    if not os.path.exists(DATABASE):
        conn = create_connection()
        try:
            if not check_tables(conn):
                conn.execute("""
                CREATE TABLE items (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    description TEXT,
                    price REAL NOT NULL,
                    tax REAL
                )
                """)
                conn.commit()
                print(f"数据库表已成功创建于 {DATABASE}")
            else:
                print(f"数据库表已存在于 {DATABASE}")
        finally:
            conn.close()

# 先执行初始化
init_db()

class DatabaseConnection:
    def __init__(self):
        self.conn = create_connection()
        
    def __enter__(self):
        return self.conn
        
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.conn.close()
        
    def execute(self, *args, **kwargs):
        return self.conn.execute(*args, **kwargs)
        
    def commit(self):
        return self.conn.commit()

# 获取数据库连接
def get_db():
    return DatabaseConnection()
